<template>
  <view class="chat-detail">
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="nav-content">
        <view class="nav-back" @tap="goBack">
          <uni-icons type="left" size="20" color="#333"></uni-icons>
        </view>
        <text class="nav-title">{{ targetUserInfo.nickname }}</text>
      </view>
    </view>

    <!-- 聊天消息列表 -->
    <scroll-view 
      class="message-list" 
      scroll-y 
      :scroll-into-view="scrollToMessageId"
      :refresher-enabled="true"
      :refresher-triggered="isRefreshing"
      @refresherrefresh="onRefresh"
      @scrolltolower="loadMore"
      :scroll-with-animation="true"
      :scroll-anchoring="true"
    >
      <!-- 加载更多提示 -->
      <uni-load-more :status="loadMoreStatus" v-if="hasMore"></uni-load-more>
      
      <!-- 消息列表 -->
      <view class="message-wrapper">
        <view 
          v-for="message in messages" 
          :key="message.id"
          :id="'msg-' + message.id"
          :class="['message-item', message.isSelf ? 'self' : 'other']"
        >
          <!-- 对方头像 -->
          <image 
            v-if="!message.isSelf" 
            class="avatar" 
            :src="targetUserInfo.avatar" 
            mode="aspectFill"
          ></image>
          
          <!-- 消息内容 -->
          <view class="message-content">
            <text class="time" v-if="showMessageTime(message)">{{ formatTime(message.createTime) }}</text>
            <view class="bubble">{{ message.content }}</view>
          </view>
          
          <!-- 自己的头像 -->
          <image 
            v-if="message.isSelf" 
            class="avatar" 
            :src="userInfo.avatar" 
            mode="aspectFill"
          ></image>
        </view>
      </view>
    </scroll-view>

    <!-- 底部输入框 -->
    <view class="input-box" :style="{ bottom: keyboardHeight + 'px' }">
      <input 
        class="message-input"
        v-model="messageContent"
        type="text"
        confirm-type="send"
        placeholder="请输入消息"
        @confirm="sendMessage"
        @focus="onInputFocus"
        @blur="onInputBlur"
      />
      <button 
        class="send-btn" 
        :disabled="!messageContent.trim()" 
        @tap="sendMessage"
      >发送</button>
    </view>
  </view>
</template>

<script>
import { formatTime } from '@/utils/date'

// 添加消息类型枚举
const MESSAGE_TYPE = {
  TEXT: 1,
  IMAGE: 2,
  FILE: 3
}

export default {
  data() {
    return {
      targetUserInfo: {
        userId: '',
        nickname: '',
        avatar: ''
      },
      userInfo: {
        avatar: ''
      },
      messages: [],
      messageContent: '',
      page: 1,
      pageSize: 20,
      hasMore: true,
      isRefreshing: false,
      loadMoreStatus: 'more',
      scrollToMessageId: '',
      keyboardHeight: 0,
      lastMessageTime: 0, // 用于控制时间显示间隔
      loading: false,
      messageTypes: MESSAGE_TYPE // 添加消息类型到data中
    }
  },

  onLoad(options) {
    // 获取目标用户信息
    this.targetUserInfo = {
      userId: options.userId,
      nickname: decodeURIComponent(options.nickname || ''),
      avatar: decodeURIComponent(options.avatar || '')
    }
    
    // 获取当前用户信息
    const userInfo = uni.getStorageSync('userInfo')
    this.userInfo = {
      avatar: userInfo.avatar || '/static/images/default-avatar.jpg'
    }
    
    // 加载聊天记录
    this.loadChatHistory()
    
    // 标记消息为已读
    this.markMessagesAsRead()
  },

  methods: {
    formatTime,
    
    // 返回上一页
    goBack() {
      uni.navigateBack()
    },
    
    // 加载聊天记录
    async loadChatHistory(refresh = false) {
      if (this.loading) return
      
      try {
        this.loading = true
        if (refresh) {
          this.page = 1
          this.messages = []
          this.hasMore = true
        }
        
        const res = await this.$api.message.chat.getChatHistory(this.targetUserInfo.userId, {
          pageNum: this.page,
          pageSize: this.pageSize
        })
        
        if (res.code === 200 && res.data) {
          const { records, total } = res.data
          
          // 格式化消息数据
          const formattedMessages = records.map(msg => ({
            id: msg.id,
            content: msg.content,
            createTime: msg.createTime,
            isSelf: msg.senderId === uni.getStorageSync('userInfo').id
          }))
          
          // 反转消息顺序，最新的消息在底部
          this.messages = refresh ? 
            formattedMessages.reverse() : 
            [...formattedMessages.reverse(), ...this.messages]
            
          this.hasMore = this.messages.length < total
          this.loadMoreStatus = this.hasMore ? 'more' : 'noMore'
          
          if (refresh) {
            this.scrollToBottom()
          }
          
          this.page++
        }
      } catch (error) {
        console.error('加载聊天记录失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
        if (refresh) {
          this.isRefreshing = false
        }
      }
    },
    
    // 发送消息
    async sendMessage() {
      if (!this.messageContent.trim()) return
      
      try {
        const messageDTO = {
          receiverId: this.targetUserInfo.userId,
          content: this.messageContent.trim(),
          type: MESSAGE_TYPE.TEXT // 使用数字类型
        }
        
        // 添加到消息列表（乐观更新）
        const tempMessage = {
          id: Date.now(),
          content: this.messageContent,
          createTime: new Date(),
          isSelf: true
        }
        this.messages.push(tempMessage)
        this.scrollToBottom()
        
        // 清空输入框
        this.messageContent = ''
        
        // 发送消息
        await this.$api.message.chat.sendMessage(messageDTO)
        
      } catch (error) {
        console.error('发送消息失败:', error)
        uni.showToast({
          title: '发送失败',
          icon: 'none'
        })
      }
    },
    
    // 标记消息为已读
    async markMessagesAsRead() {
      try {
        await this.$api.message.chat.markAsRead(this.targetUserInfo.userId)
      } catch (error) {
        console.error('标记已读失败:', error)
      }
    },
    
    // 控制消息时间显示
    showMessageTime(message) {
      const currentTime = new Date(message.createTime).getTime()
      if (currentTime - this.lastMessageTime > 5 * 60 * 1000) { // 5分钟间隔显示时间
        this.lastMessageTime = currentTime
        return true
      }
      return false
    },
    
    // 滚动到底部
    scrollToBottom() {
      if (this.messages.length > 0) {
        this.scrollToMessageId = 'msg-' + this.messages[this.messages.length - 1].id
      }
    },
    
    // 处理输入框焦点事件
    onInputFocus(e) {
      this.keyboardHeight = e.detail.height || 0
      this.$nextTick(() => {
        this.scrollToBottom()
      })
    },
    
    onInputBlur() {
      this.keyboardHeight = 0
    },
    
    // 下拉刷新
    async onRefresh() {
      this.isRefreshing = true
      await this.loadChatHistory(true)
    },
    
    // 加载更多
    loadMore() {
      if (this.hasMore && !this.loading) {
        this.loadChatHistory()
      }
    }
  }
}
</script>

<style lang="scss">
.chat-detail {
  min-height: 100vh;
  background-color: #f8f8f8;
  display: flex;
  flex-direction: column;
}

.nav-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
  background-color: #fff;
  
  .nav-content {
    position: relative;
    height: 88rpx;
    padding-top: var(--status-bar-height);
    display: flex;
    align-items: center;
    justify-content: center;
    
    .nav-back {
      position: absolute;
      left: 30rpx;
      padding: 20rpx;
    }
    
    .nav-title {
      font-size: 32rpx;
      color: #333;
      font-weight: bold;
    }
  }
}

.message-list {
  flex: 1;
  padding: 20rpx;
  margin: calc(var(--status-bar-height) + 88rpx) 0 120rpx;
  
  .message-wrapper {
    .message-item {
      display: flex;
      margin-bottom: 30rpx;
      
      .avatar {
        width: 80rpx;
        height: 80rpx;
        border-radius: 50%;
        margin: 0 20rpx;
      }
      
      .message-content {
        max-width: 60%;
        
        .time {
          font-size: 24rpx;
          color: #999;
          text-align: center;
          margin: 20rpx 0;
          display: block;
        }
        
        .bubble {
          padding: 20rpx;
          border-radius: 12rpx;
          font-size: 28rpx;
          line-height: 1.4;
          word-break: break-all;
        }
      }
      
      &.other {
        justify-content: flex-start;
        
        .bubble {
          background-color: #fff;
          color: #333;
          border-top-left-radius: 4rpx;
        }
      }
      
      &.self {
        justify-content: flex-end;
        
        .bubble {
          background-color: #0066ff;
          color: #fff;
          border-top-right-radius: 4rpx;
        }
      }
    }
  }
}

.input-box {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #fff;
  padding: 20rpx;
  display: flex;
  align-items: center;
  border-top: 1rpx solid #f5f5f5;
  
  .message-input {
    flex: 1;
    height: 80rpx;
    background-color: #f5f5f5;
    border-radius: 40rpx;
    padding: 0 30rpx;
    font-size: 28rpx;
    margin-right: 20rpx;
  }
  
  .send-btn {
    width: 120rpx;
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    background-color: #0066ff;
    color: #fff;
    font-size: 28rpx;
    border-radius: 40rpx;
    padding: 0;
    
    &[disabled] {
      background-color: #ccc;
    }
  }
}
</style> 